const jwt = require('jsonwebtoken');
const helper = require('../../util/helper');
const config = require('../../config/environment/index');
const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const common = require('../../core/common');
const stringUtils = require('../../core/util/StringUtils');
const _ = require('lodash');

exports.add = async(ctx) => {
  let project_name = ctx.request.body.project_name || '';
  let address = ctx.request.body.address || '';
  let landAgent_id = ctx.request.body.landAgent_id || 0;
  let remark = ctx.request.body.remark || '';
  let create_user_id = ctx.user.id || '';
  if (project_name === '' || address === '' || landAgent_id <= 0) {
      ctx.body = {
          result: 201,
          message: "请检查参数"
      };
  }else{
      try {
          let existLandAgent = await mysql.query(`SELECT * FROM landagent WHERE landAgent_id = ?`, landAgent_id);
          if (existLandAgent.length <= 0){
              ctx.body = {
                  result: 204,
                  message: "找不到房开商"
              };
              return
          }
          existLandAgent[0].proj_numb++;
          let newProject = {
              project_name,
              address,
              landAgent_id,
              remark,
              create_user_id,
              status:0,
              create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
              update_time: moment().format('YYYY-MM-DD HH:mm:ss'),
          };
          await new Promise((resolve, reject) => {
              var trans = mysql.Client.startTransaction();
              trans.query(`INSERT INTO project SET ?`,newProject, function(err, info) {
                  if(err){
                      trans.rollback();
                      ctx.body = {
                          result: 202,
                          message: "新增项目失败"
                      };
                      resolve(ctx);
                  } else{
                      trans.query(`UPDATE landagent SET ? WHERE landagent_id = ? `,[existLandAgent[0],existLandAgent[0].landAgent_id], function(err) {
                          if(err){
                              trans.rollback();
                              ctx.body = {
                                  result: 202,
                                  message: "新增楼幢失败"
                              };
                          } else{
                              trans.commit();
                              ctx.body = {
                                  result: 200,
                                  id: info.insertId,
                                  message: "新增项目成功"
                              };
                          }
                          resolve(ctx);
                      });
                  }
              });
              trans.execute();
          });
      }catch (e) {
          ctx.body = {
              result: 205,
              message: "错误"+e.toString()
          };
      }
  }
}

exports.delete = async(ctx) => {
    let project_id = ctx.params.project_id || 0;
    if (project_id <= 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return
    }
    try{
        let existRows = await mysql.query(`SELECT * FROM project WHERE project_id = ?`, project_id);
        if (existRows.length <= 0){
            ctx.body = {
                result: 202,
                message: "对象不存在或已删除"
            };
        }else{
            let existLandAgent = await mysql.query(`SELECT * FROM landagent WHERE landAgent_id = ?`, existRows[0].landAgent_id);
            if (existLandAgent.length <= 0){
                ctx.body = {
                    result: 204,
                    message: "找不到房开商"
                };
                return
            }
            existLandAgent[0].proj_numb--;
            await new Promise((resolve, reject) => {
                var trans = mysql.Client.startTransaction();
                trans.query(`UPDATE landagent SET ? WHERE landagent_id = ? `,[existLandAgent[0],existLandAgent[0].landAgent_id], function(err, info) {
                    if(err){
                        trans.rollback();
                        ctx.body = {
                            result: 203,
                            message: "删除失败"
                        };
                        resolve(ctx);
                    } else{
                        trans.query(`delete from project WHERE project_id = ?`, project_id, function(err) {
                            if(err){
                                trans.rollback();
                                ctx.body = {
                                    result: 202,
                                    message: "对象不存在或已删除"
                                };
                            } else{
                                trans.commit();
                                ctx.body = {
                                    result: 200,
                                    message: "删除成功"
                                };
                            }
                            resolve(ctx);
                        });
                    }
                });
                trans.execute();
            });
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.update = async(ctx) => {
    let project_id = ctx.request.body.project_id || 0;
    let project_name = ctx.request.body.project_name || '';
    let address = ctx.request.body.address || '';
    let landAgent_id = ctx.request.body.landAgent_id || 0;
    let remark = ctx.request.body.remark || '';
    let status = ctx.request.body.status || 0;

    if (project_id <= 0 || project_name === '' || address === '' || landAgent_id <= 0 || status < 0 ) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
    }else{
        try {
            let existLandAgent = await mysql.query(`SELECT * FROM landagent WHERE landAgent_id = ?`, landAgent_id);
            if (existLandAgent.length <= 0){
                ctx.body = {
                    result: 204,
                    message: "找不到房开商"
                };
                return
            }
            let selectProject = await mysql.query(`SELECT * FROM project WHERE project_id = ?`, [project_id]);
            if (selectProject.length > 0) {
                console.log('selectProject:', selectProject);
                selectProject[0].project_name = project_name;
                selectProject[0].landAgent_id = landAgent_id;
                selectProject[0].address = address;
                selectProject[0].remark = remark;
                selectProject[0].status = status;
                selectProject[0].update_time = moment().format('YYYY-MM-DD HH:mm:ss');
                ret = await mysql.query(`UPDATE project SET ? WHERE project_id = ?`, [selectProject[0],selectProject[0].project_id]);
                if (!ret || ret.insertId === -1) {
                    ctx.body = {
                        result: 202,
                        message: "更新项目失败"
                    };
                } else {
                    ctx.body = {
                        result: 200,
                        message: "更新项目成功"
                    };
                }
            } else {
                ctx.body = {
                    result: 203,
                    message: "项目不存在或者已删除"
                };
            }
        }catch (e) {
            ctx.body = {
                result: 205,
                message: "错误"+e.toString()
            };
        }
    }
}

exports.getList = async(ctx) => {
    let create_user_id = ctx.user.id || '';
    let counts = ctx.query.counts || 10;
    let indexfrom = ctx.query.indexfrom || 0;
    let keyword = ctx.query.keyword ? ctx.query.keyword.trim() : '';

    if (create_user_id === ''){
        ctx.body = {
            result: 201,
            message: "无效的用户id"
        };
    } else {
        try {
            let needColumn = ' v_project_detail.project_id,v_project_detail.project_name,v_project_detail.create_time,v_project_detail.update_time,v_project_detail.create_user_id,v_project_detail.address,v_project_detail.landAgent_name,v_project_detail.remark,v_project_detail.status ';
            let results = (keyword === '') ?
                await mysql.query(`SELECT ` + needColumn + ` FROM v_project_detail WHERE create_user_id = ? ORDER BY project_id LIMIT ${indexfrom}, ${counts}`,[create_user_id])
                : await mysql.query(`SELECT ` + needColumn + ` FROM v_project_detail WHERE create_user_id = ? and project_name like ? ORDER BY project_id LIMIT ${indexfrom}, ${counts}`,[create_user_id,'%'+keyword +'%']);
            let totalResult = (keyword === '') ? await mysql.query(`SELECT COUNT(project_id) AS total FROM v_project_detail WHERE create_user_id = ?`,create_user_id)
                : await mysql.query(`SELECT COUNT(project_id) AS total FROM v_project_detail WHERE create_user_id = ? and project_name like ? `,[create_user_id,'%'+keyword +'%']);
            ctx.body = {
                result: 200,
                list:results,
                totalpage:Math.ceil((totalResult.length > 0 ? totalResult[0].total : 0)/counts),
                totalcounts:totalResult.length > 0 ? totalResult[0].total : 0,
                message: "查询成功"
            };
        }catch (e) {
            ctx.body = {
                result: 205,
                message: "错误" + e.toString()
            };
        }
    }
}

exports.getDetail = async(ctx) => {
    let create_user_id = ctx.user.id || '';
    let project_id = ctx.params.project_id || 0;

    if (create_user_id === ''){
        ctx.body = {
            result: 201,
            message: "无效的用户id"
        };
        return;
    }
    if (project_id <= 0){
        ctx.body = {
            result: 202,
            message: "无效的项目id"
        };
        return;
    }
    try {
        let needColumn = ' v_project_detail.project_id,v_project_detail.project_name,v_project_detail.create_time,v_project_detail.update_time,v_project_detail.proj_numb,v_project_detail.note ';
        let results = await mysql.query(`SELECT` + needColumn + `FROM v_project_detail WHERE project_id = ?`,[project_id]);
        if (results.length > 0){
            ctx.body = {
                result: 200,
                resultInfo:results[0],
                message: "查询成功"
            };
        } else{
            ctx.body = {
                result: 203,
                message: "查询失败"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误" + e.toString()
        };
    }
}




